package net.zjitc.controller;

import net.zjitc.common.ResponseResult;
import net.zjitc.entity.Goods;
import net.zjitc.entity.GoodsPics;
import net.zjitc.exception.GoodsException;
import net.zjitc.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 毛钰深
 * @create 2022/2/1
 */
@RestController
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @PreAuthorize("hasAuthority('153')")
    @GetMapping("/goods")
    public ResponseResult selectPageGoods(@RequestParam(required = false) String query,
                                         @RequestParam(required = false) Integer pagenum,
                                         @RequestParam(required = false) Integer pagesize){
        ResponseResult res;
        try {
            res = goodsService.selectPageGoods(query,pagenum,pagesize);
        } catch (GoodsException e) {
            res=new ResponseResult();
            res.setError(e.getMessage());
        }
        return res;
    }

    @PreAuthorize("hasAuthority('105')")
    @PostMapping("/goods")
    public ResponseResult addGoods(@RequestBody Goods goods){
        ResponseResult res;
        try{
            res=goodsService.addGoods(goods);
        }catch(GoodsException e){
            res=new ResponseResult();
            res.setError(e.getMessage());
        }

        return res;
    }

    @PreAuthorize("hasAuthority('153')")
    @GetMapping("/goods/{id}")
    public ResponseResult selectById(@PathVariable Integer id){
        ResponseResult res;
        try {
            res=goodsService.selectById(id);
        } catch (GoodsException e) {
            res=new ResponseResult();
            res.setError(e.getMessage());
        }
        return res;
    }

    @PreAuthorize("hasAuthority('116')")
    @PutMapping("/goods/{id}")
    public ResponseResult updateGoods(@PathVariable Integer id,@RequestBody Goods goods){
        ResponseResult res;
        try {
            goods.setGoods_id(id);
            res=goodsService.updateGoods(goods);
        } catch (GoodsException e) {
            res=new ResponseResult();
            res.setError(e.getMessage());
        }
        return res;
    }

    @PreAuthorize("hasAuthority('117')")
    @DeleteMapping("/goods/{id}")
    public ResponseResult deleteById(@PathVariable Integer id){
        return goodsService.deleteById(id);
    }

    @PreAuthorize("hasAuthority('150')")
    @PutMapping("/goods/{id}/pics")
    public ResponseResult updatePics(@PathVariable Integer id, @RequestBody List<GoodsPics> pics){
        ResponseResult res;
        try {
            res=goodsService.updatePics(id,pics);
        } catch (GoodsException e) {
            res=new ResponseResult();
            res.setError(e.getMessage());
        }
        return res;
    }
}
